from pypinyin import pinyin, Style
from model_interfaces import ITextToPhonemModel
import re

class ChinesePhonemConverter(ITextToPhonemModel):
    def convertToPhonem(self, text: str) -> str:
        """
        将汉字文本转换为带声调数字的拼音字符串。
        例如: "你好" -> "ni3 hao3"
        """
        if not text or not re.search(r'[\u4e00-\u9fa5]', text):
            return ""
        
        # 使用pypinyin获取带声调的拼音列表，例如: [['nǐ'], ['hǎo']]
        try:
            pinyin_list = pinyin(text, style=Style.TONE3, neutral_tone_with_fifth_tone=True)
        except TypeError:
            # 兼容旧版本pypinyin
            pinyin_list = pinyin(text, style=Style.TONE3)
        
        # 将列表展平并拼接成字符串
        phonems = " ".join([item[0] for item in pinyin_list if item])
        return phonems

def get_phonem_converter():
    """
    转换器工厂函数
    """
    return ChinesePhonemConverter() 